package com.topscomm.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.topscomm.mms.pojo.MmsUserAccessInfoEntity;
import com.topscomm.mms.service.impl.MmsUserAccessInfoService;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.util.UserAgentUtil;
import com.topscomm.tap.common.SessionUserBean;
import com.topscomm.tap.threadlocal.ThreadLocalContext;
/**
 * url拦截器，获取用户url请求相关信息
 * @description:
 * @author: hudeyong
 * @date: 2021年06月21日上午10:49:39
 * @modify:
 */
@Component
public class MmsAccessInterceptor implements HandlerInterceptor {
	@Autowired
	MmsUserAccessInfoService mmsUserAccessInfoService;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String url = request.getRequestURI();
		// 获取用户登录信息
		SessionUserBean userBean = ThreadLocalContext.sessionUserBeanThreadLocal.get();
		// 获取User-Agent信息
		String userAgentString = request.getHeader("User-Agent");
		//获取浏览器信息
		String browserInfo = UserAgentUtil.getBrowserName(userAgentString) + UserAgentUtil.getBrowserVersion(userAgentString);
		MmsUserAccessInfoEntity userAccessInfoEntity = new MmsUserAccessInfoEntity();
		if(userBean!=null) {
			userAccessInfoEntity.setUsercode(userBean.getUser().getCode());
			userAccessInfoEntity.setUsername(userBean.getUser().getName());
			userAccessInfoEntity.setOrgcode(userBean.getOrg().getCode());
			userAccessInfoEntity.setDeptcode(userBean.getDept().getCode());
			userAccessInfoEntity.setAccessbrowser(browserInfo);
			userAccessInfoEntity.setAccesstime(new Date());
			userAccessInfoEntity.setAccessip(BaseUtil.getIPAddress(request));
			String loginmode = "PC";
			//获取访问连接
			String requestUrl = request.getRequestURI();
			userAccessInfoEntity.setAccessurl(requestUrl);
			//获取登录方式
			String deviceType = request.getParameter("deviceType");
			if(!StringUtil.isEmpty(deviceType)) {
				loginmode = deviceType;
			}
			userAccessInfoEntity.setLoginmode(loginmode);
			mmsUserAccessInfoService.insert(userAccessInfoEntity);	
		}			
		return HandlerInterceptor.super.preHandle(request, response, handler);
	}
}
